package tsscharts;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Date;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;

import tsscharts.intf.IWindow;

public class Main {

	public static void main(String[] args) {
		long start = new Date().getTime();
		Context context = Context.enter();
		try {
			//
			Scriptable standard = context.initStandardObjects();
			//
			Scriptable window = new NativeJavaObject(standard,
					Factory.createWindow(), IWindow.class);
			window.setParentScope(standard);
			//
			Scriptable scope = new NativeObject();
			scope.setParentScope(window);
			//
			loadFile(context, scope, "js/jquery-1.4.2.js");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			Context.exit();
		}
		long end = new Date().getTime();
		System.out.println("during: " + (end - start));
	}

	private static void loadFile(Context context, Scriptable scope, String fn)
			throws Exception {
		String script = readFile(fn);
		context.evaluateString(scope, script, fn, 1, null);
	}

	private static String readFile(String fn) throws Exception {
		StringBuilder sb = new StringBuilder();
		File file = new File(fn);
		InputStream is = new FileInputStream(file);
		Reader reader = new InputStreamReader(is);
		int BUFFER_SIZE = 1024, count = 0;
		char[] buffer = new char[BUFFER_SIZE];
		for (;;) {
			count = reader.read(buffer, 0, BUFFER_SIZE);
			if (count == -1) {
				break;
			}
			sb.append(buffer, 0, count);
		}
		return sb.toString();
	}

}
